# 1、涨幅3-5%
# 2、排除量比小于 1的
# 3、排除换手率低于5%或者高于10%的
# 4、排除流通市值大于200亿或低于50亿的
# 5、价格在五日均线以上
# 6、去除ST
# 7、去除创业板
# 8、价格3-30元

import akshare as ak
import pandas as pd
from datetime import datetime

def get_current_date_formatted():
    # 获取当前日期
    current_date = datetime.now()
    # 格式化日期
    formatted_date = current_date.strftime("%Y_%m_%d")
    return formatted_date

get_current = get_current_date_formatted()

def stock_filter():
    # 1. 获取 A股实时行情
    df = ak.stock_zh_a_spot_em()

    # 2. 按条件逐步过滤
    # 涨幅 3% - 5%
    df = df[(df["涨跌幅"] >= 3) & (df["涨跌幅"] <= 5)]

    # 量比 >= 1
    df = df[df["量比"] >= 1]

    # 换手率 5% - 10%
    df = df[(df["换手率"] >= 5) & (df["换手率"] <= 10)]

    # 流通市值 50亿 - 200亿
    df = df[(df["流通市值"] >= 50e8) & (df["流通市值"] <= 200e8)]

    # 最新价 3 - 30 元
    df = df[(df["最新价"] >= 3) & (df["最新价"] <= 30)]

    # 去除 ST
    df = df[~df["名称"].str.contains("ST")]

    # 去除创业板（300/301开头）
    df = df[~df["代码"].str.startswith(("300", "301"))]

    # 3. 检查五日均线条件
    passed = []
    for code in df["代码"]:
        try:
            daily = ak.stock_zh_a_hist(symbol=code, period="daily", adjust="qfq")
            daily["收盘"] = pd.to_numeric(daily["收盘"])
            daily["MA5"] = daily["收盘"].rolling(5).mean()
            latest = daily.iloc[-1]
            if latest["收盘"] > latest["MA5"]:
                passed.append(code)
        except Exception as e:
            print(f"获取 {code} 日线数据失败：{e}")

    # 4. 最终结果
    result = df[df["代码"].isin(passed)]
    result = result[["代码", "名称", "最新价", "涨跌幅", "换手率", "量比", "流通市值"]]

    # 保存结果到 CSV
    result.to_csv("stock_filter_result_" + get_current + ".csv", index=False, encoding="utf-8-sig")

    print("符合条件的股票：")
    print(result)

if __name__ == "__main__":
    stock_filter()
